<template>
  <div class="system-bg">
    <el-card class="user-card" shadow="hover">
      <div slot="header" class="card-header-horizontal">
        <div class="header-title">为成员 "{{ memberName }}" 选择配偶</div>
        <div class="header-btn-group">
          <el-button class="outline-btn" icon="el-icon-arrow-left" @click="$router.go(-1)">
            返回
          </el-button>
        </div>
      </div>

      <!-- 已选择的配偶 -->
      <el-alert
        v-if="selectedSpouses.length > 0"
        title="已选择的配偶（按顺序排列）"
        type="success"
        :closable="false"
        style="margin-bottom: 20px"
        class="selected-spouses-alert"
      >
        <div class="selected-spouses">
          <div
            v-for="(spouse, index) in selectedSpouses"
            :key="spouse.id"
            class="selected-spouse-item"
          >
            <div class="spouse-order">{{ getSpouseOrderText(index) }}</div>
            <el-tag
              closable
              @close="removeSelectedSpouse(spouse)"
              class="spouse-tag"
            >
              {{ spouse.name }} ({{ spouse.gender === 'M' ? '男' : '女' }})
            </el-tag>
          </div>
        </div>
        <div class="spouse-order-info">
          <small>顺序说明：正室/正夫、侧室/侧夫、三房/三夫、四房/四夫...（可拖拽调整顺序）</small>
        </div>
      </el-alert>

      <!-- 配偶选择器 -->
      <SpouseSelector
        :selectedSpouseIds="selectedSpouseIds"
        @confirm="handleSpouseConfirm"
      />

      <!-- 确认按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="handleSave" :loading="saving" class="save-btn">
          保存配偶关系
        </el-button>
        <el-button @click="$router.go(-1)" class="cancel-btn">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import SpouseSelector from '@/components/SpouseSelector.vue'
import { getMemberDetail } from '@/api/member'
import { getMemberSpouses, addMemberSpouse, deleteMemberSpouse } from '@/api/member'

export default {
  name: 'MemberSpouseSelector',
  components: {
    SpouseSelector
  },
  data() {
    return {
      memberId: null,
      memberName: '',
      selectedSpouses: [],
      selectedSpouseIds: [],
      saving: false
    }
  },
  async mounted() {
    // 兼容 params 和 query
    this.memberId = this.$route.params.memberId || this.$route.query.memberId
    console.log('mounted memberId:', this.memberId)
    if (this.memberId) {
      await this.loadMemberInfo()
      await this.loadCurrentSpouses()
    } else {
      console.warn('未获取到memberId，页面无法加载成员信息')
    }
  },
  methods: {
    // 加载成员信息
    async loadMemberInfo() {
      try {
        const response = await getMemberDetail(this.memberId)
        console.log('成员详情接口返回：', response)
        // 兼容request拦截器已解包，直接用response.name
        if (response && response.name) {
          this.memberName = response.name
          console.log('赋值memberName:', this.memberName)
        } else {
          console.warn('成员详情接口无有效数据')
        }
      } catch (error) {
        this.$message.error('加载成员信息失败')
        console.error(error)
      }
    },

    // 加载当前配偶
    async loadCurrentSpouses() {
      try {
        const response = await getMemberSpouses(this.memberId)
        if (response && response.data) {
          this.selectedSpouses = response.data
          this.selectedSpouseIds = response.data.map(spouse => spouse.id)
        }
      } catch (error) {
        console.error('加载当前配偶失败:', error)
      }
    },

    // 处理配偶选择确认
    handleSpouseConfirm(selectedSpouses) {
      this.selectedSpouses = selectedSpouses
      this.selectedSpouseIds = selectedSpouses.map(spouse => spouse.id)
      console.log('选中的配偶:', this.selectedSpouses)
    },

    // 移除已选择的配偶
    removeSelectedSpouse(spouse) {
      const index = this.selectedSpouses.findIndex(s => s.id === spouse.id)
      if (index > -1) {
        this.selectedSpouses.splice(index, 1)
        this.selectedSpouseIds = this.selectedSpouses.map(s => s.id)
      }
    },

    // 获取配偶排序文本
    getSpouseOrderText(index) {
      // 根据配偶性别显示不同称谓
      const spouse = this.selectedSpouses[index]
      const isMaleSpouse = spouse && spouse.gender === 'M'
      
      if (index === 0) {
        return isMaleSpouse ? '正夫' : '正室';
      } else if (index === 1) {
        return isMaleSpouse ? '侧夫' : '侧室';
      } else if (index === 2) {
        return isMaleSpouse ? '三夫' : '三房';
      } else if (index === 3) {
        return isMaleSpouse ? '四夫' : '四房';
      } else if (index === 4) {
        return isMaleSpouse ? '五夫' : '五房';
      } else if (index === 5) {
        return isMaleSpouse ? '六夫' : '六房';
      } else if (index === 6) {
        return isMaleSpouse ? '七夫' : '七房';
      } else if (index === 7) {
        return isMaleSpouse ? '八夫' : '八房';
      } else if (index === 8) {
        return isMaleSpouse ? '九夫' : '九房';
      } else if (index === 9) {
        return isMaleSpouse ? '十夫' : '十房';
      } else {
        return isMaleSpouse ? `${index + 1}夫` : `${index + 1}房`; // 默认显示序号
      }
    },

    // 保存配偶关系
    async handleSave() {
      if (this.selectedSpouseIds.length === 0) {
        this.$message.warning('请至少选择一个配偶')
        return
      }

      this.saving = true
      try {
        // 获取当前成员的配偶关系
        const currentSpouses = await getMemberSpouses(this.memberId)
        const currentSpouseIds = currentSpouses ? currentSpouses.map(s => s.spouseId) : []
        
        // 删除不再选中的配偶关系
        for (const spouse of currentSpouses || []) {
          if (!this.selectedSpouseIds.includes(spouse.spouseId)) {
            try {
              await deleteMemberSpouse(spouse.id) // 使用配偶关系ID，不是配偶ID
            } catch (error) {
              console.error('删除配偶关系失败:', error)
            }
          }
        }

        // 添加新选中的配偶关系，按顺序设置
        for (let i = 0; i < this.selectedSpouses.length; i++) {
          const spouse = this.selectedSpouses[i]
          // 检查是否已经存在这个配偶关系
          const existingSpouse = currentSpouses ? currentSpouses.find(s => s.spouseId === spouse.id) : null
          
          if (!existingSpouse) {
            // 只有不存在的配偶关系才添加
            await addMemberSpouse({
              memberId: this.memberId,
              spouseId: spouse.id,
              relationType: i === 0 ? 'spouse' : 'concubine', // 第一个为正室，其他为侧室
              sortOrder: i + 1 // 按顺序设置
            })
          } else {
            // 更新现有配偶关系的顺序
            await this.updateMemberSpouseOrder(existingSpouse.id, i + 1)
          }
        }

        this.$message.success('配偶关系保存成功')
        this.$router.go(-1)
      } catch (error) {
        this.$message.error('保存配偶关系失败')
        console.error(error)
      } finally {
        this.saving = false
      }
    },

    // 更新配偶关系顺序
    async updateMemberSpouseOrder(relationId, newOrder) {
      try {
        // 这里需要调用更新配偶关系的API
        // 暂时使用现有的API，实际项目中可能需要添加专门的更新API
        console.log(`更新配偶关系顺序: relationId=${relationId}, newOrder=${newOrder}`)
      } catch (error) {
        console.error('更新配偶关系顺序失败:', error)
      }
    }
  }
}
</script>

<style scoped>
.system-bg {
  min-height: 80vh;
  background: linear-gradient(135deg, #f4f6fa 60%, #e0e7ff 100%);
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding: 48px 0;
  animation: fadeIn 0.8s;
}

.user-card {
  width: 1100px;
  border-radius: 18px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.10);
  background: rgba(255,255,255,0.95);
  transition: box-shadow 0.3s;
}

.card-header-horizontal {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 8px;
}

.header-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: left;
}

.header-btn-group {
  display: flex;
  align-items: center;
  background: none;
  border-radius: 0;
  padding: 0;
  box-shadow: none;
}

.header-btn-group .el-button {
  margin-right: 8px;
  height: 34px;
  font-size: 15px;
  padding: 0 18px;
  display: flex;
  align-items: center;
}

.outline-btn {
  background: #fff;
  border: 1px solid #6a82fb;
  color: #6a82fb;
  margin-right: 8px;
  transition: all 0.2s;
}

.outline-btn:hover {
  background: #6a82fb;
  color: #fff;
}

.selected-spouses-alert {
  border-radius: 10px;
  margin-bottom: 20px;
}

.selected-spouses {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.selected-spouse-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.spouse-order {
  background-color: #f0f9eb;
  color: #67c23a;
  border: 1px solid #e1f3d8;
  border-radius: 4px;
  padding: 2px 6px;
  font-size: 12px;
  font-weight: bold;
  min-width: 20px;
  text-align: center;
}

/* 正室/正夫特殊样式 */
.selected-spouse-item:first-child .spouse-order {
  background-color: #e1f3d8;
  color: #67c23a;
  border-color: #67c23a;
  font-weight: bold;
}

/* 侧室/侧夫样式 */
.selected-spouse-item:not(:first-child) .spouse-order {
  background-color: #fdf6ec;
  color: #e6a23c;
  border-color: #f5dab1;
}



.spouse-tag {
  background: #e8f4fd;
  border: 1px solid #409EFF;
  color: #409EFF;
  border-radius: 16px;
  padding: 4px 12px;
  font-size: 13px;
  transition: all 0.2s;
  font-weight: 500;
}

.spouse-tag:hover {
  background: #409EFF;
  color: #fff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.spouse-order-info {
  margin-top: 10px;
  text-align: right;
  color: #909399;
  font-size: 12px;
}

.action-buttons {
  margin-top: 30px;
  text-align: center;
  display: flex;
  justify-content: center;
  gap: 16px;
}

.save-btn {
  background: linear-gradient(90deg, #6a82fb 0%, #fc5c7d 100%);
  border: none;
  color: #fff;
  font-weight: bold;
  padding: 12px 24px;
  border-radius: 8px;
  transition: all 0.3s;
}

.save-btn:hover {
  background: linear-gradient(90deg, #fc5c7d 0%, #6a82fb 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(106, 130, 251, 0.3);
}

.cancel-btn {
  background: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
  padding: 12px 24px;
  border-radius: 8px;
  transition: all 0.3s;
}

.cancel-btn:hover {
  background: #f5f7fa;
  border-color: #6a82fb;
  color: #6a82fb;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style> 